<?php
/*
 * 函数：网站配置获取函数
 * @param  string $k      可选，配置名称
 * @return array          用户数据
*/
function setting($k='')
{
    if($k==''){
        $setting =M('setting')->field('k,v')->select();
        foreach($setting as $k=>$v){
            $config[$v['k']] = $v['v'];
        }
        return $config;
    }else{
        $model = M('setting');
        $result=$model->where("k='{$k}'")->find();
        return $result['v'];
    }
}

/*
 * 函数：验证码验证函数
 * @param  string $code    验证码文本
 * @param  string $id      钥匙
 * @return array           bool值
*/
//验证码检测
function checkverify($code,$id='')
{
    $verify = new \Think\Verify();
    return $verify->check($code,$id);
}
/**
 *
 * 函数：日志记录
 * @param  string $log   日志内容。
 * @param  string $name （可选）用户名。
 *
 **/
function addlog($log,$name=false)
{
    $Model = M('log');
    if(!$name){
        $auth = cookie('auth');
        list($identifier, $token) = explode(',', $auth);
        if (ctype_alnum($identifier) && ctype_alnum($token)) {
            $user = M('member')->field('user')->where(array('identifier'=>$identifier))->find();
            $data['name'] = $user['user'];
        }else{
            $data['name'] = '';
        }
    }else{
        $data['name'] = $name;
    }
    $data['t'] = time();
    $data['ip'] = $_SERVER["REMOTE_ADDR"];
    $data['log'] = $log;
    $Model->data($data)->add();
}


/**
 * 函数：加密
 * @param string            密码
 * @return string           加密后的密码
 */
function password($password)
{
    /*
    *后续整强有力的加密函数
    */
	return md5('Q'.$password.'W');
//    return md5($password);

}

/**
 * 随机字符
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string
 */
function random($length=6, $type='string', $convert=0)
{
    $config = array(
        'number'=>'1234567890',
        'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if(!isset($config[$type])) $type = 'string';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) -1;
    for($i = 0; $i < $length; $i++){
        $code .= $string{mt_rand(0, $strlen)};
    }
    if(!empty($convert)){
        $code = ($convert > 0)? strtoupper($code) : strtolower($code);
    }
    return $code;
}
/**
 *
 * 函数：获取用户信息
 * @param  int $uid      用户ID。
 * @param  string $name  数据列（如：'uid'、'uid,user'）
 *
 **/
function member($uid,$field=false)
{
    $model = M('Member');
    if($field){
        return $model ->field($field)-> where(array('uid'=>$uid)) -> find();
    }else{
        return $model -> where(array('uid'=>$uid)) -> find();
    }
}


/**
 * @method 多维数组转字符串
 * @param type $array
 * @return type $srting
 */
function arrayToString($arr)
{
    if (is_array($arr)){
        return implode(',', array_map('arrayToString', $arr));
    }
    return $arr;
}
/**
 * 多维数组转换成一维数组
 * @param array $tree
 * @param array $children
 * @return array
 */

function getNewArr($tree, $children='children')
{
    $imparr = array();
    foreach($tree as $val) {
        if(isset($val[$children])) {
            $newArr = $val[$children];
            unset($val[$children]);
            $imparr[] = $val;
            if(is_array($newArr)) $imparr = array_merge($imparr, getNewArr($newArr,$children));
        } else {
            $imparr[] = $val;
        }
    }
    return $imparr;
}
/**
 * 保存调整函数转换成一维数组
 * @param array $tree
 * @param array $children
 * @return array
 */

function menuNewArr($tree, $children='children',$pid =0)
{
    $imparr = array();
    for($i=0;$i<count($tree);$i++){
        if(isset($tree[$i][$children])) {
            $newArr = $tree[$i][$children];
            unset($tree[$i][$children]);
            $tree[$i]['id'] = $tree[$i]['id'];
            $tree[$i]['pid'] = $pid;
            $tree[$i]['o'] = $i;
            $imparr[] = $tree[$i];
            if(is_array($newArr)) $imparr = array_merge($imparr,menuNewArr($newArr,$children,$tree[$i]['id']));
        } else {
            $imparr[$i]['id'] = $tree[$i]['id'];
            $imparr[$i]['pid'] = $pid;
            $imparr[$i]['o'] = $i;
        }

    }

    return $imparr;
}

/**
 * 批量修改更新数据函数
 * @param array $table_name 表名
 * @param array $data       数据
 * @param array $field      字段
 * @return array
 */
//批量修改  data二维数组 field关键字段  参考ci 批量修改函数 传参方式
function batch_update($table_name='',$data=array(),$field='')
{
    if(!$table_name||!$data||!$field){
        return false;
    }else{
        $sql='UPDATE '.$table_name;
    }
    $con=array();
    $con_sql=array();
    $fields=array();
    foreach ($data as $key => $value) {
        $x=0;
        foreach ($value as $k => $v) {
            if($k!=$field&&!$con[$x]&&$x==0){
                $con[$x]=" set {$k} = (CASE {$field} ";
            }elseif($k!=$field&&!$con[$x]&&$x>0){
                $con[$x]="  {$k} = (CASE {$field} ";
            }
            if($k!=$field){
                $temp=$value[$field];
                $con_sql[$x].=   " WHEN '{$temp}' THEN '{$v}' ";
                $x++;
            }
        }
        $temp=$value[$field];
        if(!in_array($temp,$fields)){
            $fields[]=$temp;
        }
    }
    $num=count($con)-1;
    foreach ($con as $key => $value) {
        foreach ($con_sql as $k => $v) {
            if($k==$key&&$key<$num){
                $sql.=$value.$v.' end),';
            }elseif($k==$key&&$key==$num){
                $sql.=$value.$v.' end)';
            }
        }
    }
    $str=implode(',',$fields);
    $sql.=" where {$field} in({$str})";
    $res=M($table_name)->execute($sql);
    return $res;
}

/**
 * 时间转换成过去多久时间格式
 * @param array $time    时间戳
 * @return string
 */
function beenTime($time)
{
    $time = (int) substr($time, 0, 10);
    $int = time() - $time;
    $str = '';
    if ($int <= 2){
        $str = sprintf('刚刚', $int);
    }elseif ($int < 60){
        $str = sprintf('%d秒前', $int);
    }elseif ($int < 3600){
        $str = sprintf('%d分钟前', floor($int / 60));
    }elseif ($int < 86400){
        $str = sprintf('%d小时前', floor($int / 3600));
    }elseif ($int < 2592000){
        $str = sprintf('%d天前', floor($int / 86400));
    }else{
        $str = date('Y年m月d日 H:i:s', $time);
    }
    return $str;
}

/**
 * 菜单栏目获得样式
 * @param array $mold    菜单类型
 * @return string
 */

function getMenuInfo($mold)
{
    switch ($mold) {
        case '2':
            $style = 'warning';
            break;
        case '3':
            $style = 'success';
            break;
        default:
            $style = 'info';
            break;
    }
    return $style;
}

/**
 * 部门类型
 * @param array $pid    类型id
 * @return string
 */

function getDeptType($pid)
{
    switch ($pid) {
        case '0':
            $type = '总管部门';
            break;
        default:
            $type = '子部门';
            break;
    }
    return $type;
}

/**
 * 员工类型
 * @param array $type    类型id
 * @return string
 */
function getMemberType($type)
{
    switch ($type) {
        case '1':
            $str = '创始人';
            break;
        case '2':
            $str = '总监/总经理';
            break;
        case '3':
            $str = '经理';
            break;
        default:
            $str = '普通员工';
            break;
    }
    return $str;
}

//文件图片上传函数
function UpImage($callBack="image",$width=100,$height=100,$image="")
{
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width='.$width.' height="'.$height.'"  src="'.U('Upload/uploadpic').'?Width='.$width.'&Height='.$height.'&BackCall='.$callBack.'&Img='.$image.'"></iframe>
         <input type="hidden" name="'.$callBack.'" id="'.$callBack.'">';
}
function BatchImage($callBack="image",$height=300,$image="")
{
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" src="'.U('Upload/batchpic').'?BackCall='.$callBack.'&Img='.$image.'"></iframe>
		<input type="hidden" name="'.$callBack.'" id="'.$callBack.'">';
}

function UpFile($callBack="file",$width=100,$height=100,$file="")
{
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" width='.$width.' height="'.$height.'"  src="'.U('Upload/uploadfile').'?Width='.$width.'&Height='.$height.'&BackCall='.$callBack.'&Files='.$file.'"></iframe>
         <input type="hidden" name="'.$callBack.'" id="'.$callBack.'">';
}
function BatchFile($callBack="file",$height=300,$file="")
{
    echo '<iframe scrolling="no" frameborder="0" border="0" onload="this.height=this.contentWindow.document.body.scrollHeight;this.width=this.contentWindow.document.body.scrollWidth;" src="'.U('Upload/batchfile').'?BackCall='.$callBack.'&Files='.$file.'"></iframe>
		<input type="hidden" name="'.$callBack.'" id="'.$callBack.'">';
}

/**
 *
 * 函数：搜索描红的函数
 * @param  string $string      字符串
 * @param  string $words       替换的文字
 * @return  处理好的数据
 *
 **/
function SearchWords($string,$words='')
{
    if(!empty($words) || !empty($string)){
        $string = str_replace("$words",'<font color="red"'.">".$words."</font>",$string);
        return $string;
    }
    return $string;
}

/**
 * 获取笔记类型
 * @param string $source    类型id
 * @return string
 */
function getWordSource($source)
{
    switch ($source) {
        case '1':
            $str = '工作笔记';
            break;
        case '2':
            $str = '代码笔记';
            break;
        case '3':
            $str = '摘抄笔记';
            break;
        default:
            $str = '私人笔记';
            break;
    }
    return $str;
}


/**
 * 不在常用ip地址登录返回描红信息
 * @param string $ip    ip地址
 * @param string $name    用户名
 * @return string
 */

function errorIp($ip,$name)
{

    //获取当前ip地址
    $nowip = get_client_ip();
    //如果是常用ip地址则直接返回字符串
    if($ip == $nowip ){
        $str = '<font color="#888"'.">登录IP：".$ip."</font>";
    }else{
        //记数ip地址数量判断是否是常用ip
        $count  =   M('log')->where("name='{$name}' AND ip='{$ip}'")->count();
        if($count > 20){
            $str = '<font color="#888"'.">登录IP：".$ip."</font>";
        }else{
            $str = '<font color="red"'.">异常IP：".$ip."</font>";
        }
    }

    return $str;

}

//判断是否是手机访问
function is_mobile_request()
{
    $_SERVER['ALL_HTTP'] = isset($_SERVER['ALL_HTTP']) ? $_SERVER['ALL_HTTP'] : '';
    $mobile_browser = '0';
    if (preg_match('/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|iphone|ipad|ipod|android|xoom)/i', strtolower($_SERVER['HTTP_USER_AGENT'])))
        $mobile_browser++;
    if ((isset($_SERVER['HTTP_ACCEPT'])) and (strpos(strtolower($_SERVER['HTTP_ACCEPT']), 'applicationnd.wap.xhtml+xml') !== false))
        $mobile_browser++;
    if (isset($_SERVER['HTTP_X_WAP_PROFILE']))
        $mobile_browser++;
    if (isset($_SERVER['HTTP_PROFILE']))
        $mobile_browser++;
    $mobile_ua = strtolower(substr($_SERVER['HTTP_USER_AGENT'], 0, 4));
    $mobile_agents = array(
        'w3c ', 'acs-', 'alav', 'alca', 'amoi', 'audi', 'avan', 'benq', 'bird', 'blac',
        'blaz', 'brew', 'cell', 'cldc', 'cmd-', 'dang', 'doco', 'eric', 'hipt', 'inno',
        'ipaq', 'java', 'jigs', 'kddi', 'keji', 'leno', 'lg-c', 'lg-d', 'lg-g', 'lge-',
        'maui', 'maxo', 'midp', 'mits', 'mmef', 'mobi', 'mot-', 'moto', 'mwbp', 'nec-',
        'newt', 'noki', 'oper', 'palm', 'pana', 'pant', 'phil', 'play', 'port', 'prox',
        'qwap', 'sage', 'sams', 'sany', 'sch-', 'sec-', 'send', 'seri', 'sgh-', 'shar',
        'sie-', 'siem', 'smal', 'smar', 'sony', 'sph-', 'symb', 't-mo', 'teli', 'tim-',
        'tosh', 'tsm-', 'upg1', 'upsi', 'vk-v', 'voda', 'wap-', 'wapa', 'wapi', 'wapp',
        'wapr', 'webc', 'winw', 'winw', 'xda', 'xda-'
    );
    if (in_array($mobile_ua, $mobile_agents))
        $mobile_browser++;
    if (strpos(strtolower($_SERVER['ALL_HTTP']), 'operamini') !== false)
        $mobile_browser++;
    // Pre-final check to reset everything if the user is on Windows
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows') !== false)
        $mobile_browser = 0;
    // But WP7 is also Windows, with a slightly different characteristic
    if (strpos(strtolower($_SERVER['HTTP_USER_AGENT']), 'windows phone') !== false)
        $mobile_browser++;
    if ($mobile_browser > 0){
        return true;
    }else{
        return false;
    }
}

/**
 * 不在常用ip地址登录返回描红信息
 * @param string  $sutas 状态id
 * @return string
 */
function getCtmerStu($stutas)
{
    switch ($stutas) {
        case '1':
            $str = '<span class="label label-primary">已验证</span>';
            break;
        case '2':
            $str = '<span class="label label-warning">已失效</span>';
            break;

        default:
            $str =  '<span class="label label-info">未验证</span>';
            break;
    }
    return $str;
}

/**
 * 不在常用ip地址登录返回描红信息
 * @param string  $id 状态id
 * @return string
 */
function getCtmerSex($sid)
{
    switch ($sid) {
        case '1':
            $str = '<i class="fa fa-child">帅哥</i>';
            break;
        case '2':
            $str = '<i class="fa fa-child">美女</i>';
            break;

        default:
            $str =  '<i class="fa fa-child">保密</i>';
            break;
    }
    return $str;
}

/**
 * 获取颜色
 * @param string  $id 状态id
 * @return string
 */
function getColor($sid)
{
    switch ($sid) {
        case '1':
            $str = '#06c';
            break;
        case '2':
            $str = '#f30';
            break;
        case '3':
            $str = 'purple';
            break;
        case '4':
            $str = 'blue';
            break;

        default:
            $str =  '#360';
            break;
    }
    return $str;
}

/**
 * 获取图标
 * @param string  $sid 状态id
 * @return string
 */
function getIcon($sid)
{
    switch ($sid) {
        case '1':
            $str = 'file-text';
            break;
        case '2':
            $str = 'user-md';
            break;
        case '3':
            $str = 'phone';
            break;
        default:
            $str =  'coffee';
            break;
    }
    return $str;
}

/**
 * 获取待办状态
 * @param string  $id 状态id
 * @return string
 */
function getNoteStu($sid)
{
    switch ($sid) {
        case '1':
            $str =  '<span class="label label-primary">优先级：一般</span>';
            break;
        case '2':
            $str =  '<span class="label label-info">优先级：优先</span>';
            break;
        case '3':
            $str = '<span class="label label-warning">优先级：加急</span>';
            break;
        case '4':
            $str = '<span class="label label-success">优先级：已完成</span>';
            break;

        default:
            $str =  '<span class="label label-default">优先级：最低</span>';
            break;
    }
    return $str;
}

/**
 * 判断是否为图片
 * @param string  $type 状态id
 * @return string
 */
function getIsImage($type)
{
    $img = array('gif','jpg','jpeg','bmp','png');
    if(in_array($type,$img)){
        return true;
    }

    return false;
}

/**
 * 获取文件类型图标
 * @param string  $type 状态id
 * @return string
 */
function getFileIcon($type)
{
    switch ($type) {
        case 'mp3':
            $str = 'music';
            break;
        case 'doc':
            $str = 'file-text';
            break;
        case 'pdf':
            $str = 'file-pdf-o';
            break;
        case 'xls':
            $str = 'file-excel-o';
            break;
        case 'xlsx':
            $str = 'file-excel-o';
            break;
        case 'csv':
            $str = 'file-excel-o';
            break;
        case 'zip':
            $str = 'file-zip-o';
            break;
        default:
            $str =  'file';
            break;
    }
    return $str;
}

//文件下载函数
function download($file_url,$new_name='')
{
    if(substr($file_url,0,1)=='/'){
        $file_url =substr($file_url,1);
    }
    if(!isset($file_url)||trim($file_url)==''){
        echo '500';
    }
    if(!file_exists($file_url)){ //检查文件是否存在
        echo '404';
    }
    $file_name=basename($file_url);
    $file_type=explode('.',$file_url);
    $file_type=$file_type[count($file_type)-1];
    $file_name=trim($new_name=='')?$file_name:urlencode($new_name);
    $file_type=fopen($file_url,'r'); //打开文件
    //输入文件标签
    header("Content-type: application/octet-stream");
    header("Accept-Ranges: bytes");
    header("Accept-Length: ".filesize($file_url));
    header("Content-Disposition: attachment; filename=".$file_name);
    //输出文件内容
    echo fread($file_type,filesize($file_url));
    fclose($file_type);
}

//删除函数
function delFile($file)
{
    $isdel = strrchr($file, '.');
    if($isdel !=='.php'){
        if($file==""):return false;endif;
        if (!unlink($file)){
            echo ("Error deleting $file");
        }else{
            echo ("Deleted $file");
        }
    }
    return false;
}

/**
 * 获取动态类型名称
 * @param string  $source 状态id
 * @return string
 */
function getNewsType($source)
{
    //1、公司动态、2、分享动态、3、短话
    switch($source){
        case '1':
            $str = "公司通告";
            break;
        case '2':
            $str = "分享";
            break;
        case '3':
            $str = "短说说";
            break;
        default:
            $str = '发布';
            break;
    }

    return $str;
}

/**
 * 保存点赞信息
 * @param string  $id 动态id
 * @param string $uid 用户id
 * @return string
 */
function savePrez($id,$uid)
{
    //读入旧数据
    $old = cookie("prez{$uid}");
    //添加新数据
    $new = array($id,);
    if($old){
        //添加新数据
        $prez =  array_merge_recursive($old,$new);
    }else{
        //写入数据
        $prez = $new;
    }
    //保存三天
    cookie("prez{$uid}",$prez,3600*24*3);

}

/**
 * 获取点赞信息
 * @param string  $id 动态id
 * @param string $uid 用户id
 * @return string
 */

function getPrez($id,$uid,$num)
{

    $prez = cookie("prez{$uid}");
    if(in_array($id, $prez)){
        return '<a class="btn btn-xs btn-white red-bg" '.'"><i class="fa fa-thumbs-up"></i> 已赞</a> ';
    }
    return '<a class="btn btn-xs btn-white prez" val="'.$id.'"><i class="fa fa-thumbs-up"></i> 赞('.$num.') </a> ';

}

/**
 * 获取报表类型信息
 * @param string  $id 类型父级id
 * @return string
 */

function getRptFname($id=0)
{
    $data = M('reports')->field('pid')->where("id={$id}")->find();
    $data = M('reports')->field('name')->where("id={$data['pid']}")->find();
    $name = $data['name'];
    if($name){
        return $name;
    }
    return false;
}

/**
 * 获取报表类型信息
 * @param string  $pid 类型父级id
 * @return string
 */

function getRptName($id=0)
{
    $data = M('reports')->field('name')->where("id={$id}")->find();
    $name = $data['name'];
    if($name){
        return $name;
    }
    return false;
}

/**
 * 获取报表审核名称
 * @param string  $status 状态id
 * @return string
 */
function getRptType($status)
{
    //0未审核,1已审核,2不通过
    switch($status){
        case '1':
            $str = "已审核";
            break;
        case '2':
            $str = "不通过";
            break;
        default:
            $str = '未审核';
            break;
    }

    return $str;
}

/**
 * 获取上级id
 * @param string  $pid 状态id
 * @return string
 */
function getFid($pid){
    //已经知道的pid获取他的上级id
    $data =  M('reports')->field('id,pid')->where("id=$pid")->find();
    //返回上级id并使用
    return $data['pid'];
}


/**
 * 分数计算
 * @param string  $score 状态id
 * @param string  $cpt 倍率
 * @return decimal
 */
function getScore($score,$cpt=1){

    //计算分数
    $score = floatval($score*$cpt);
    //保留 ".00"
    $score = number_format($score,2);
    //返回计算好的分数
    return $score;

}

/**
 * 获取月报审核状态
 * @param string  $stu 状态id
 * @return string
 */
function getMonthlyStatus($stu){
//    0、未提交1、已提交2经理审核、3总监审核
    $arr = array(
        '0'=>'月报未提交',
        '1'=>'月报已提交',
        '2'=>'经理已审核',
        '3'=>'总监已审核',
    );
    return $arr[$stu];

}

/**
 * 获取月报等级
 * @param int  $ases 工作得分
 * @param int  $duty 工作责任得分
 * @param int  $active 主动、积极性得分
 * @param int  $observe 遵守公司制度得分
 * @return string
 */
function getMonthlyDj($ases,$duty,$active,$observe){

    $ases_score = getScore($ases,0.8);
    $duty_score = getScore($duty,0.06);
    $active_score = getScore($active,0.06);
    $observe_score = getScore($observe,0.08);
    $aggregate = $ases_score + $duty_score + $active_score + $observe_score;
    //获取等级
    if($aggregate>0 && $aggregate <=60){
        return 'D';
    }
    if($aggregate>60 && $aggregate <=90){
        return 'C';
    }
    if($aggregate>90 && $aggregate <=100){
        return 'B';
    }
    if($aggregate >100){
        return 'A';
    }

    return false;
}

/**
 * 获取月报系数
 * @param int  $ases 工作得分
 * @param int  $duty 工作责任得分
 * @param int  $active 主动、积极性得分
 * @param int  $observe 遵守公司制度得分
 * @return string
 */
function getMonthlyJx($ases,$duty,$active,$observe){

    $ases_score = getScore($ases,0.8);
    $duty_score = getScore($duty,0.06);
    $active_score = getScore($active,0.06);
    $observe_score = getScore($observe,0.08);
    $aggregate = $ases_score + $duty_score + $active_score + $observe_score;
    //获取绩效
    if($aggregate>0 && $aggregate <=60){
        return '0.0';
    }
    if($aggregate>60 && $aggregate <=90){
        return '1.0';
    }
    if($aggregate>90 && $aggregate <=100){
        return '1.5';
    }
    if($aggregate>100){
        return '2.0';
    }

    return false;

}

/**
 * 获取两个时间之间的时间差
 * @param int   $begin_time 相差时间
 * @param int   $end_time 结束时间
 * @return string
 */
function timediff( $begin_time, $end_time )
{
    if ( $begin_time < $end_time ) {
        $starttime = $begin_time;
        $endtime = $end_time;
    } else {
        $starttime = $end_time;
        $endtime = $begin_time;
    }
    $timediff = $endtime - $starttime;
    $days = intval( $timediff / 86400 );
    $remain = $timediff % 86400;
    $hours = intval( $remain / 3600 );
    $remain = $remain % 3600;
    $mins = intval( $remain / 60 );
    $secs = $remain % 60;
    $res = array( "day" => $days, "hour" => $hours, "min" => $mins, "sec" => $secs );
    return $res['hour'].'时'.$res['min'].'分';
}